import re
import os
import json
from minio import Minio
from minio.error import S3Error

# 初始化 MinIO 客户端
endpoint = "192.168.50.103:9000"  # 替换为你的 MinIO 服务地址
secure = False  # 如果是 HTTP 使用 False
client = Minio(
    endpoint,
    access_key="gytZQZdmOhe2JZc6yr1k",  # 替换为你的访问密钥
    secret_key="TGs7wgbxOuvYCFZ2D5jXuoCOBTlehxJNnODXn0id",  # 替换为你的密钥
    secure=secure
)

bucket_name = "pic"

# 创建存储桶（如果不存在）
try:
    if not client.bucket_exists(bucket_name):
        client.make_bucket(bucket_name)
    print(f"Bucket '{bucket_name}' is ready.")
except S3Error as e:
    print(f"Error checking/creating bucket: {e}")

# 设置存储桶为公开访问
try:
    policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {"AWS": ["*"]},
                "Action": ["s3:GetObject"],
                "Resource": [f"arn:aws:s3:::{bucket_name}/*"]
            }
        ]
    }
    policy_json = json.dumps(policy)
    client.set_bucket_policy(bucket_name, policy_json)
    print(f"Bucket '{bucket_name}' is now publicly accessible.")
except S3Error as e:
    print(f"Error setting bucket policy: {e}")

# 正则表达式匹配 Markdown 中的图像链接
image_pattern = re.compile(r'!\[.*?\]\((.*?)\)')


def upload_image_to_minio(file_path, object_name):
    """上传文件到 MinIO，并返回公开 URL"""
    try:
        client.fput_object(bucket_name, object_name, file_path)
        print(f"'{object_name}' is successfully uploaded.")
    except S3Error as e:
        print(f"Error uploading file: {e}")
        return None

    # 构造对象的公开 URL
    protocol = "http" if not secure else "https"
    object_url = f"{protocol}://{endpoint}/{bucket_name}/{object_name}"
    return object_url


def process_markdown_file(md_file_path, images_dir):
    with open(md_file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 查找所有的图像链接
    image_links = image_pattern.findall(content)
    if not image_links:
        print("No images found in the markdown file.")
        return

    # 替换图像链接
    for image_link in image_links:
        local_image_path = os.path.join(images_dir, image_link)
        if os.path.exists(local_image_path):
            # 上传图片到 MinIO
            object_name = f"kb/{os.path.basename(image_link)}"
            public_url = upload_image_to_minio(local_image_path, object_name)

            # 替换 markdown 文件中的链接
            if public_url:
                content = content.replace(image_link, public_url)
        else:
            print(f"Image not found: {local_image_path}")

    # 将替换后的内容写回文件（或写入新文件）
    new_md_file_path = os.path.splitext(md_file_path)[0] + "_updated.md"
    with open(new_md_file_path, 'w', encoding='utf-8') as file:
        file.write(content)

    print(f"Updated markdown file saved as: {new_md_file_path}")


# 使用示例
md_file_path = "../output/KUKA机器人编程3_TrainerGuide_P3KSS8_Programming 3_V1_zh/auto/KUKA机器人编程3_TrainerGuide_P3KSS8_Programming 3_V1_zh.md"  # 替换为你的 Markdown 文件路径
images_dir = "../output/KUKA机器人编程3_TrainerGuide_P3KSS8_Programming 3_V1_zh/auto"  # 替换为存放图片的目录路径

process_markdown_file(md_file_path, images_dir)
